import UIKit

extension UIViewController {
  func enableSmartTapToDismissKeyboard() {
    let tapGesture = UITapGestureRecognizer(
      target: self, action: #selector(smartDismissKeyboardByTap))
    tapGesture.cancelsTouchesInView = false
    view.addGestureRecognizer(tapGesture)
  }

  @objc private func smartDismissKeyboardByTap(_ gesture: UITapGestureRecognizer) {
    let location = gesture.location(in: view)
    let tappedView = view.hitTest(location, with: nil)

    // 如果点击的是非 UI 控件区域（例如空白背景），才收起键盘
    if shouldDismissKeyboard(for: tappedView) {
      view.endEditing(true)
    }
  }

  /// 判断点击的 view 是否是需要忽略的控件（不收起键盘）
  private func shouldDismissKeyboard(for view: UIView?) -> Bool {
    guard let view = view else { return true }

    // 你可以在这里添加想排除的控件类型
    if view is UIControl || view is UITextView {
      return false
    }

    return true
  }
}
